<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { usePlanStore } from '../stores/planStore'
import { useContainerStore } from '../stores/containerStore'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Link } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
// 导入容器API
import { createContainer, bindContainerToPlan ,createContainerAndBindPlan ,endContainerApi} from '../api/container'

const router = useRouter()
const route = useRoute()
const planStore = usePlanStore()
const containerStore = useContainerStore()

// 当前计划
const currentPlan = ref(null)

// 绑定的容器列表（直接从API获取的数据）
const planContainers = ref([])

// 筛选后的容器列表（根据状态筛选）
const filteredContainers = computed(() => {
  if (!containerStatusFilter.value) {
    return planContainers.value
  }
  
  return planContainers.value.filter(container => 
    container.status === containerStatusFilter.value
  )
})

// 容器状态筛选
const containerStatusFilter = ref('')

// 是否正在加载容器列表（保留用于其他可能的加载状态）
const loadingContainers = ref(false)

// 编辑计划对话框
const showEditDialog = ref(false)

// 绑定容器对话框
const showBindDialog = ref(false)

// 创建容器对话框
const showCreateContainerDialog = ref(false)

// 容器选择
const selectedContainerIds = ref([])

// 创建容器表单
const containerForm = ref({
  title: '',
  description: '',
  category: '',
  estimatedTime: 30
})

// 计划表单（用于编辑）
const planForm = ref({
  title: '',
  description: '',
  category: '',
  date: '',
  startTime: '',
  endTime: '',
  priority: 'medium',
  color: '#409EFF'
})

// 分类选项
const categoryOptions = [
  { label: '工作', value: '工作' },
  { label: '学习', value: '学习' },
  { label: '阅读', value: '阅读' },
  { label: '写作', value: '写作' },
  { label: '思考', value: '思考' },
  { label: '运动', value: '运动' },
  { label: '其他', value: '其他' }
]

// 优先级选项
const priorityOptions = [
  { label: '高', value: 'high', color: '#F56C6C' },
  { label: '中', value: 'medium', color: '#E6A23C' },
  { label: '低', value: 'low', color: '#909399' }
]

// 颜色选项
const colorOptions = [
  '#409EFF', '#67C23A', '#E6A23C', '#F56C6C', 
  '#909399', '#95d475', '#40a9ff', '#ff7875'
]

// 获取可绑定的容器（排除已绑定的）
const availableContainers = computed(() => {
  if (!currentPlan.value) return []
  
  return containerStore.containers.filter(container => {
    // 确保类型匹配：将容器ID和计划containerIds都转换为字符串进行匹配
    const containerIdStr = String(container.id)
    return !currentPlan.value.containerIds.some(planContainerId => 
      String(planContainerId) === containerIdStr
    )
  })
})

// 获取容器状态文本
function getContainerStatusText(status) {
  const statusMap = {
    'pending': '待开始',
    'active': '进行中', 
    'in-progress': '进行中',
    'completed': '已完成',
    'paused': '已暂停'
  }
  return statusMap[status] || '未知状态'
}

// 获取容器状态颜色类型
function getContainerStatusType(status) {
  const typeMap = {
    'pending': 'info',
    'active': 'warning',
    'in-progress': 'warning', 
    'completed': 'success',
    'paused': 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取优先级颜色
function getPriorityColor(priority) {
  const option = priorityOptions.find(opt => opt.value === priority)
  return option ? option.color : '#909399'
}

// 获取状态文本
function getStatusText(status) {
  const statusMap = {
    'pending': '待开始',
    'in-progress': '进行中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

// 获取状态颜色
function getStatusColor(status) {
  const colorMap = {
    'pending': '#909399',
    'in-progress': '#409EFF',
    'completed': '#67C23A',
    'cancelled': '#F56C6C'
  }
  return colorMap[status] || '#909399'
}

// 编辑计划
function editPlan() {
  planForm.value = { ...currentPlan.value }
  showEditDialog.value = true
}

// 保存计划编辑
async function savePlanEdit() {
  if (!planForm.value.title.trim()) {
    ElMessage.warning('请输入计划标题')
    return
  }
  
  try {
    const numericPlanId = Number(currentPlan.value.id)
    await planStore.updatePlan(numericPlanId, planForm.value)
    currentPlan.value = { ...currentPlan.value, ...planForm.value }
    ElMessage.success('计划更新成功')
    showEditDialog.value = false
  } catch (error) {
    ElMessage.error('更新计划失败：' + error.message)
  }
}

// 筛选容器状态
function filterContainersByStatus(status) {
  if (containerStatusFilter.value === status) {
    // 如果点击的是当前已选中的状态，则取消筛选
    containerStatusFilter.value = ''
  } else {
    // 设置新的筛选状态
    containerStatusFilter.value = status
  }
}

// 删除计划
function deletePlan() {
  ElMessageBox.confirm('确定要删除这个计划吗？', '确认删除', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const numericPlanId = Number(currentPlan.value.id)
      await planStore.deletePlan(numericPlanId)
      ElMessage.success('计划已删除')
      router.push('/plan-board')
    } catch (error) {
      ElMessage.error('删除计划失败：' + error.message)
    }
  }).catch(() => {})
}

// 打开绑定容器对话框
function openBindDialog() {
  selectedContainerIds.value = []
  showBindDialog.value = true
}

// 打开创建容器对话框
function openCreateContainerDialog() {
  // 重置表单
  containerForm.value = {
    title: '',
    description: '',
    category: '',
    estimatedTime: 30
  }
  showCreateContainerDialog.value = true
}

// 创建容器并绑定到当前计划
async function createAndBindContainer() {
  if (!containerForm.value.title.trim()) {
    ElMessage.warning('请输入容器名称')
    return
  }
  
  try {
    // 1. 调用API创建容器
    const containerData = {
      title: containerForm.value.title.trim(),
      description: containerForm.value.description?.trim() || '',
      category: containerForm.value.category || '工作',
      // estimatedTime: containerForm.value.estimatedTime,todo 后端没有，暂不支持
      // tags: "写死的，待修改 todo",
      // relatedPostId: containerForm.value.relatedPostId || null,
      // relatedReplyId: containerForm.value.relatedReplyId || null
    };
    const numericPlanId = Number(currentPlan.value.id);
    const response = await createContainerAndBindPlan(numericPlanId, containerData);
    
    // 3.根据当前的计划id去查询所有容器并渲染
    // 使用已有的getPlanContainers方法替代不存在的getContainersByPlanId方法
    const getPlan = await planStore.getPlanContainers(numericPlanId);
    console.log('获取计划容器:', getPlan);
    
    // 获取后展示计划容器
    // 更新当前计划的容器列表，确保新创建的容器显示在列表中
    if (currentPlan.value) {
      // 从API响应中获取新创建的容器ID
      // 根据API文档，响应格式为 { code: 200, message: "容器绑定成功", data: 1758530482337, timestamp: 1760856052289 }
      const newContainerId = response.data;
      
      // 确保currentPlan.value.containerIds存在且为数组
      if (!currentPlan.value.containerIds) {
        currentPlan.value.containerIds = [];
      }
      
      // 检查新容器ID是否已存在于计划中，避免重复添加
      if (newContainerId && !currentPlan.value.containerIds.includes(newContainerId)) {
        // 使用展开运算符创建新数组，触发Vue的响应式更新
        currentPlan.value.containerIds = [...currentPlan.value.containerIds, newContainerId];
        console.log('已将新容器添加到计划中:', newContainerId);
      }
      
      // 触发容器列表的重新计算
      // planContainers是计算属性，会自动更新
      console.log('计划容器列表已更新，当前容器数量:', currentPlan.value.containerIds.length);
      
      // 同时更新容器存储，确保新创建的容器可以在列表中显示
      await containerStore.initFromAPI();
      
      // 重新获取计划绑定的容器列表，确保显示最新数据
      const updatedContainers = await planStore.getPlanContainers(numericPlanId);
      planContainers.value = updatedContainers || [];
    }
    
    ElMessage.success('容器创建成功并已绑定到计划')
    showCreateContainerDialog.value = false
  } catch (error) {
    console.error('创建并绑定容器失败:', error)
    console.error('错误详情:', error.response || error.message || error);
    ElMessage.error('创建容器失败：' + error.message)
  }
}

// 绑定选中的容器
async function bindSelectedContainers() {
  try {
    const numericPlanId = Number(currentPlan.value.id)
    for (const containerId of selectedContainerIds.value) {
      await planStore.bindContainer(numericPlanId, containerId)
    }
    
    // 更新当前计划数据
    currentPlan.value.containerIds.push(...selectedContainerIds.value)
    
    // 重新获取计划绑定的容器列表，确保显示最新数据
    const updatedContainers = await planStore.getPlanContainers(numericPlanId);
    planContainers.value = updatedContainers || [];
    
    ElMessage.success(`已绑定 ${selectedContainerIds.value.length} 个容器`)
    showBindDialog.value = false
  } catch (error) {
    ElMessage.error('绑定容器失败：' + error.message)
  }
}

// 解绑容器
function unbindContainer(containerId) {
  ElMessageBox.confirm('确定要解绑这个容器吗？', '确认解绑', {
    confirmButtonText: '解绑',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const numericPlanId = Number(currentPlan.value.id)
      await planStore.unbindContainer(numericPlanId, containerId)
      
      // 从当前计划中移除容器ID
      const index = currentPlan.value.containerIds.indexOf(containerId)
      if (index > -1) {
        currentPlan.value.containerIds.splice(index, 1)
      }
      
      // 重新获取计划绑定的容器列表，确保显示最新数据
      const updatedContainers = await planStore.getPlanContainers(numericPlanId);
      planContainers.value = updatedContainers || [];
      
      ElMessage.success('容器已解绑')
    } catch (error) {
      ElMessage.error('解绑容器失败：' + error.message)
    }
  }).catch(() => {})
}

// 查看容器详情
function viewContainer(container) {
  router.push({
    path: '/container',
    query: { id: container.id, autoStart: 'true' }
  })
}

// 查看容器评估
function viewContainerEvaluation(container) {
  if (container.status === 'completed' && container.evaluation) {
    // 显示评估详情
    ElMessageBox.alert(
      `<div>
        <p><strong>效果评分:</strong> ${container.evaluation.effectivenessScore}/5</p>
        <p><strong>正向因素:</strong> ${container.evaluation.positiveTags.join(', ')}</p>
        <p><strong>负向因素:</strong> ${container.evaluation.negativeTags.join(', ')}</p>
        <p><strong>经验笔记:</strong> ${container.evaluation.notes}</p>
      </div>`,
      '容器评估详情',
      {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '知道了'
      }
    )
  } else {
    ElMessage.info('该容器尚未完成评估')
  }
}

// 计算时间信息
function getTimeInfo(container) {
  if (!container.startTime) return '未开始'
  
  const startTime = dayjs(container.startTime)
  const endTime = container.endTime ? dayjs(container.endTime) : dayjs()
  const duration = endTime.diff(startTime, 'minute')
  
  return `${Math.floor(duration / 60)}小时${duration % 60}分钟`
}

// 格式化日期时间
function formatDateTime(dateTimeStr) {
  return dayjs(dateTimeStr).format('YYYY-MM-DD HH:mm')
}

// 初始化数据
onMounted(async () => {
  await planStore.initFromAPI()
  await containerStore.initFromAPI()
  
  const planId = route.query.id
  if (planId) {
    // 确保 planId 是数字类型，匹配后端的 Long 类型
    const numericPlanId = Number(planId)
    const plan = planStore.plans.find(p => p.id === numericPlanId)
    
    if (plan) {
      currentPlan.value = plan
      
      // 调用API获取计划绑定的容器列表
      loadingContainers.value = true
      try {
        // 调用API接口：GET /api/plans/{planId}/containers
        const apiContainers = await planStore.getPlanContainers(numericPlanId)
        planContainers.value = apiContainers || []
        console.log('API返回的绑定容器:', apiContainers)
      } catch (error) {
        console.warn('获取计划绑定容器API调用失败:', error)
        planContainers.value = []
      } finally {
        loadingContainers.value = false
      }
      
      console.log('计划加载成功:', {
        planId: plan.id,
        containerIds: plan.containerIds,
        planContainersSize: planContainers.value.length
      })
    } else {
      console.error('未找到指定的计划, planId:', numericPlanId)
      ElMessage.error('未找到指定的计划')
      router.push('/plan-board')
    }
  } else {
    ElMessage.error('缺少计划ID参数')
    router.push('/plan-board')
  }
})

// 辅助函数：比较两个数组是否相等
function arraysEqual(arr1, arr2) {
  if (arr1.length !== arr2.length) return false
  const sorted1 = [...arr1].sort()
  const sorted2 = [...arr2].sort()
  return sorted1.every((val, idx) => val === sorted2[idx])
}

function endContainer(container) {
  ElMessageBox.confirm('确定要结束这个容器吗？', '确认结束', {
    confirmButtonText: '结束',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const numericContainerId = Number(container.id)
      await endContainerApi(numericContainerId)
      ElMessage.success('容器已结束')
      // 刷新容器列表
      const planId = route.query.id
      if (planId) {
        const numericPlanId = Number(planId)
        const updatedContainers = await planStore.getPlanContainers(numericPlanId);
        planContainers.value = updatedContainers || [];
      }
    } catch (error) {
      ElMessage.error('结束容器失败：' + error.message)
    }
  }).catch(() => {})
}
</script>

<template>
  <div class="plan-detail" v-if="currentPlan">
    <!-- 页面头部 -->
    <div class="detail-header">
      <el-button @click="router.push('/plan-board')">
        <el-icon><ArrowLeft /></el-icon>
        返回看板
      </el-button>
      
      <div class="header-actions">
        <el-button @click="editPlan">
          <el-icon><Edit /></el-icon>
          编辑
        </el-button>
        <el-button type="danger" @click="deletePlan">
          <el-icon><Delete /></el-icon>
          删除
        </el-button>
      </div>
    </div>

    <!-- 计划基本信息 -->
    <el-card class="plan-info-card">
      <template #header>
        <div class="card-header">
          <h2>{{ currentPlan.title }}</h2>
          <div class="plan-badges">
            <el-tag 
              :color="currentPlan.color" 
              effect="dark"
              v-if="currentPlan.category"
            >
              {{ currentPlan.category }}
            </el-tag>
            <el-tag 
              :color="getPriorityColor(currentPlan.priority)"
              effect="plain"
            >
              {{ priorityOptions.find(opt => opt.value === currentPlan.priority)?.label || '中' }}
            </el-tag>
            <el-tag 
              :color="getStatusColor(currentPlan.status)"
              effect="plain"
            >
              {{ getStatusText(currentPlan.status) }}
            </el-tag>
          </div>
        </div>
      </template>
      
      <div class="plan-content">
        <div class="plan-meta">
          <div class="meta-item">
            <el-icon><Calendar /></el-icon>
            <span>{{ dayjs(currentPlan.date).format('YYYY年MM月DD日 dddd') }}</span>
          </div>
          
          <div class="meta-item" v-if="currentPlan.startTime || currentPlan.endTime">
            <el-icon><Clock /></el-icon>
            <span>
              {{ currentPlan.startTime || '未设置' }}
              <span v-if="currentPlan.endTime"> - {{ currentPlan.endTime }}</span>
            </span>
          </div>
          
          <div class="meta-item">
            <el-icon><User /></el-icon>
            <span>创建于 {{ formatDateTime(currentPlan.createdAt) }}</span>
          </div>
          
          <div class="meta-item" v-if="currentPlan.updatedAt !== currentPlan.createdAt">
            <el-icon><Refresh /></el-icon>
            <span>更新于 {{ formatDateTime(currentPlan.updatedAt) }}</span>
          </div>
        </div>
        
        <div class="plan-description" v-if="currentPlan.description">
          <h4>计划描述</h4>
          <p>{{ currentPlan.description }}</p>
        </div>
        
        <!-- 容器状态筛选 -->
        <div class="status-actions">
          <h4>容器状态筛选</h4>
          <el-button-group>
            <el-button 
              @click="filterContainersByStatus('pending')" 
              :type="containerStatusFilter === 'pending' ? 'primary' : 'default'"
            >
              待开始
            </el-button>
            <el-button 
              @click="filterContainersByStatus('active')" 
              :type="containerStatusFilter === 'active' ? 'primary' : 'default'"
            >
              进行中
            </el-button>
            <el-button 
              @click="filterContainersByStatus('completed')" 
              :type="containerStatusFilter === 'completed' ? 'primary' : 'default'"
            >
              已完成
            </el-button>
            <el-button 
              @click="filterContainersByStatus('paused')" 
              :type="containerStatusFilter === 'paused' ? 'primary' : 'default'"
            >
              已暂停
            </el-button>
          </el-button-group>
        </div>
      </div>
    </el-card>

    <!-- 绑定的容器列表 -->
    <el-card class="containers-card">
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <h3>绑定的时间容器 
              <span v-if="!containerStatusFilter">({{ planContainers.length }})</span>
              <span v-else>
                ({{ filteredContainers.length }}/{{ planContainers.length }}) 
                <el-tag size="small" type="info">
                  {{ getContainerStatusText(containerStatusFilter) }}
                </el-tag>
              </span>
            </h3>
            <el-button 
              v-if="containerStatusFilter" 
              @click="containerStatusFilter = ''" 
              size="small" 
              type="text"
            >
              清除筛选
            </el-button>
          </div>
          <div class="header-buttons">
            <el-button type="success" @click="openCreateContainerDialog">
              <el-icon><Plus /></el-icon>
              创建容器
            </el-button>
            <el-button type="primary" @click="openBindDialog">
              <el-icon><Link /></el-icon>
              绑定容器
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 加载状态 -->
      <div v-if="loadingContainers" class="loading-state">
        <el-skeleton :rows="3" animated />
      </div>
      
      <!-- 空状态 -->
      <div v-else-if="planContainers.length === 0" class="empty-state">
        <el-empty description="暂无绑定的容器">
          <el-button type="primary" @click="openCreateContainerDialog">创建第一个容器</el-button>
        </el-empty>
      </div>
      
      <!-- 筛选提示 -->
      <div v-else-if="containerStatusFilter && filteredContainers.length === 0" class="filter-empty-state">
        <el-empty :description="`暂无${getContainerStatusText(containerStatusFilter)}状态的容器`">
          <el-button @click="containerStatusFilter = ''">清除筛选</el-button>
        </el-empty>
      </div>
      
      <!-- 容器列表 -->
      <div v-else class="containers-list">
        <el-card 
          v-for="container in filteredContainers" 
          :key="container.id"
          class="container-item"
          shadow="hover"
        >
          <div class="container-header">
            <div class="container-info">
              <h4>{{ container.title }}</h4>
              <el-tag 
                :type="getContainerStatusType(container.status)"
                size="small"
              >
                {{ getContainerStatusText(container.status) }}
              </el-tag>
            </div>
            
            <div class="container-actions">
              <el-dropdown>
                <el-button circle>
                  <el-icon><MoreFilled /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="viewContainer(container)">
                      <el-icon><View /></el-icon>
                      查看容器
                    </el-dropdown-item>
                    <el-dropdown-item @click="endContainer(container)">
                      <el-icon><View /></el-icon>
                      结束容器
                    </el-dropdown-item>
                    <el-dropdown-item 
                      @click="viewContainerEvaluation(container)"
                      v-if="container.status === 'completed'"
                    >
                      <el-icon><Document /></el-icon>
                      查看评估
                    </el-dropdown-item>
                    
                    <el-dropdown-item @click="unbindContainer(container.id)" divided>
                      <el-icon><Close /></el-icon>
                      解绑容器
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
          
          <div class="container-content">
            <p v-if="container.description" class="container-description">
              {{ container.description }}
            </p>
            
            <div class="container-meta">
              <div class="meta-row">
                <span class="meta-label">分类:</span>
                <el-tag size="small">{{ container.category || '未分类' }}</el-tag>
              </div>
              
              <div class="meta-row">
                <span class="meta-label">时长:</span>
                <span>{{ getTimeInfo(container) }}</span>
              </div>
              
              <div class="meta-row">
                <span class="meta-label">预估:</span>
                <span>{{ container.estimatedTime }}分钟</span>
              </div>
              
              <div class="meta-row" v-if="container.startTime">
                <span class="meta-label">开始:</span>
                <span>{{ formatDateTime(container.startTime) }}</span>
              </div>
              
              <div class="meta-row" v-if="container.endTime">
                <span class="meta-label">结束:</span>
                <span>{{ formatDateTime(container.endTime) }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </el-card>

    <!-- 编辑计划对话框 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑计划"
      width="500px"
    >
      <el-form :model="planForm" label-position="top">
        <el-form-item label="计划标题" required>
          <el-input v-model="planForm.title" placeholder="输入计划标题" />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="日期">
              <el-date-picker
                v-model="planForm.date"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="分类">
              <el-select 
                v-model="planForm.category" 
                placeholder="选择分类"
                style="width: 100%"
              >
                <el-option 
                  v-for="option in categoryOptions" 
                  :key="option.value"
                  :label="option.label" 
                  :value="option.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间">
              <el-time-picker
                v-model="planForm.startTime"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="选择开始时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="结束时间">
              <el-time-picker
                v-model="planForm.endTime"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="选择结束时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="优先级">
              <el-select 
                v-model="planForm.priority" 
                placeholder="选择优先级"
                style="width: 100%"
              >
                <el-option 
                  v-for="option in priorityOptions" 
                  :key="option.value"
                  :label="option.label" 
                  :value="option.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="颜色">
              <div class="color-picker">
                <div 
                  v-for="color in colorOptions"
                  :key="color"
                  class="color-option"
                  :class="{ active: planForm.color === color }"
                  :style="{ backgroundColor: color }"
                  @click="planForm.color = color"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="描述">
          <el-input 
            v-model="planForm.description"
            type="textarea"
            :rows="3"
            placeholder="计划描述（可选）"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="savePlanEdit">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 绑定容器对话框 -->
    <el-dialog
      v-model="showBindDialog"
      title="绑定时间容器"
      width="600px"
    >
      <div v-if="availableContainers.length === 0" class="empty-state">
        <el-empty description="暂无可绑定的容器">
          <el-button type="primary" @click="openCreateContainerDialog">
            <el-icon><Plus /></el-icon>
            创建新容器
          </el-button>
        </el-empty>
      </div>
      
      <div v-else>
        <div class="bind-header">
          <p class="bind-tip">选择要绑定到此计划的容器：</p>
          <el-button @click="openCreateContainerDialog" size="small">
            <el-icon><Plus /></el-icon>
            创建新容器
          </el-button>
        </div>
        
        <el-checkbox-group v-model="selectedContainerIds" class="container-checkbox-group">
          <div 
            v-for="container in availableContainers" 
            :key="container.id"
            class="container-checkbox-item"
          >
            <el-checkbox :label="container.id">
              <div class="checkbox-content">
                <div class="checkbox-header">
                  <strong>{{ container.title }}</strong>
                  <el-tag 
                    :type="container.status === 'completed' ? 'success' : 'info'"
                    size="small"
                  >
                    {{ container.status === 'completed' ? '已完成' : '活动中' }}
                  </el-tag>
                </div>
                <div class="checkbox-meta">
                  <span>{{ container.category || '未分类' }}</span>
                  <span>{{ getTimeInfo(container) }}</span>
                  <span>{{ formatDateTime(container.startTime || container.createdAt) }}</span>
                </div>
                <p v-if="container.description" class="checkbox-description">
                  {{ container.description }}
                </p>
              </div>
            </el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showBindDialog = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="bindSelectedContainers"
            :disabled="selectedContainerIds.length === 0"
          >
            绑定选中容器 ({{ selectedContainerIds.length }})
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 创建容器对话框 -->
    <el-dialog
      v-model="showCreateContainerDialog"
      title="创建新容器"
      width="500px"
    >
      <el-form :model="containerForm" label-position="top">
        <el-form-item label="容器名称" required>
          <el-input 
            v-model="containerForm.title" 
            placeholder="例如：编写项目文档" 
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分类">
              <el-select 
                v-model="containerForm.category" 
                placeholder="选择分类"
                style="width: 100%"
              >
                <el-option 
                  v-for="option in categoryOptions" 
                  :key="option.value"
                  :label="option.label" 
                  :value="option.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="预估时间（分钟）">
              <el-input-number 
                v-model="containerForm.estimatedTime" 
                :min="5" 
                :max="480" 
                :step="5" 
                style="width: 100%" 
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="描述（可选）">
          <el-input 
            v-model="containerForm.description"
            type="textarea"
            :rows="3"
            placeholder="简要描述你要做什么"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateContainerDialog = false">取消</el-button>
          <el-button type="primary" @click="createAndBindContainer">
            创建并绑定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.plan-detail {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.plan-info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.card-header h2,
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-title h3 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.plan-badges {
  display: flex;
  gap: 8px;
}

.plan-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.plan-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #666;
}

.plan-description h4,
.status-actions h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.containers-card {
  margin-bottom: 20px;
}

.containers-list {
  display: grid;
  gap: 15px;
}

.container-item {
  transition: all 0.3s;
}

.container-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.container-info h4 {
  margin: 0 0 5px 0;
}

.container-content {
  color: #666;
}

.container-description {
  margin: 0 0 10px 0;
  color: #303133;
}

.container-meta {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 8px;
}

.meta-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.meta-label {
  font-weight: 500;
  min-width: 40px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
}

.loading-state {
  padding: 20px;
}

.color-picker {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.color-option {
  width: 24px;
  height: 24px;
  border-radius: 4px;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.3s;
}

.color-option:hover,
.color-option.active {
  border-color: #303133;
  transform: scale(1.1);
}

.bind-tip {
  margin-bottom: 15px;
  color: #666;
}

.bind-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.bind-header .bind-tip {
  margin-bottom: 0;
  flex: 1;
}

.container-checkbox-group {
  width: 100%;
}

.container-checkbox-item {
  width: 100%;
  margin-bottom: 15px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  transition: all 0.3s;
}

.container-checkbox-item:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.checkbox-content {
  margin-left: 20px;
}

.checkbox-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.checkbox-meta {
  display: flex;
  gap: 15px;
  color: #666;
  font-size: 12px;
  margin-bottom: 5px;
}

.checkbox-description {
  margin: 5px 0 0 0;
  color: #303133;
  font-size: 13px;
}

@media (max-width: 768px) {
  .plan-detail {
    padding: 10px;
  }
  
  .detail-header {
    flex-direction: column;
    gap: 10px;
  }
  
  .plan-meta {
    flex-direction: column;
    gap: 10px;
  }
  
  .container-meta {
    grid-template-columns: 1fr;
  }
  
  .card-header {
    flex-direction: column;
    gap: 10px;
    text-align: center;
  }
}
</style>